package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.order.OrderCancelService;
import com.mall.order.OrderCoreService;
import com.mall.order.OrderDeleteService;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CancelOrderRequest;
import com.mall.order.dto.CancelOrderResponse;
import com.mall.order.dto.CreateOrderRequest;
import com.mall.order.dto.CreateOrderResponse;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.order.dto.*;
import com.mall.shopping.ICartService;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

/**
 * API网关 -- 订单请求处理
 */
@RestController
@RequestMapping("/shopping")
public class OrderController {

    // 超时时间为3s，消费时不检查服务方是否有服务
    @Reference(timeout = 3000, check = false)
    private OrderCoreService orderCoreService;

    // 超时时间为3s，消费时不检查服务方是否有服务
    @Reference(timeout = 3000, check = false)
    private OrderQueryService orderQueryService;

    @Reference(timeout = 3000, check = false)
    private OrderCancelService orderCancelService;

    // 超时时间为3s，消费时不检查服务方是否有服务
    @Reference(timeout = 3000, check = false)
    private ICartService iCartService;

    @Reference(timeout = 3000 , check = false)
    private OrderDeleteService orderDeleteService;

    /**
     * 创建订单
     *
     * @param request
     * @param servletRequest
     * @return
     */
    @PostMapping("/order")
    public ResponseData order(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest) {

        // 1.解析Json格式用户信息，拿到uid -- userId
        Long userInfo = (Long) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        request.setUserId(userInfo);

        CreateOrderResponse response = orderCoreService.createOrder(request);
        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            //清购物车缓存
            ClearCartItemRequest clearCartItemRequest = new ClearCartItemRequest();
            clearCartItemRequest.setUserId(userInfo);
            List<Long> arrayList = new ArrayList();
            List<CartProductDto> cartProductDtoList = request.getCartProductDtoList();
            for (CartProductDto cartProductDto : cartProductDtoList) {
                arrayList.add(cartProductDto.getProductId());
            }
            clearCartItemRequest.setProductIds(arrayList);
            ClearCartItemResponse clearCartItemResponse = iCartService.clearCartItemByUserID(clearCartItemRequest);


            return new ResponseUtil<>().setData(response.getOrderId());
        }

        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 取消订单
     *
     * @param request
     * @return
     */
    @PostMapping("/cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request) {

        request.setOrderId(request.getOrderId());

        CancelOrderResponse response = orderCancelService.cancelOrder(request);
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(SysRetCodeConstants.SUCCESS.getMessage());
        }
        return new ResponseUtil<>().setErrorMsg(response.getMsg());
    }

    /**
     * 获取用户所有订单
     *
     * @return
     */
    @GetMapping("/order")
    public ResponseData getOrdersByUserId(OrderListRequest request, HttpServletRequest httpServletRequest) {

        // 1.解析Json格式用户信息，拿到uid -- userId
        Long userInfo = (Long) httpServletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
//        JSONObject object = JSON.parseObject(userInfo);
//        Long uid = Long.parseLong(object.get("uid").toString());
//        request.setUserId(uid);
        request.setUserId(userInfo);

        OrderListResponse response = orderQueryService.getOrdersByUserId(request);

        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            // 封装结果集
            OrderListResult orderListResult = new OrderListResult();
            orderListResult.setData(response.getDetailInfoList());
            orderListResult.setTotal(response.getTotal());
            return new ResponseUtil().setData(orderListResult);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 查询订单详情
     */
    @GetMapping("/order/{orderId}")
    public ResponseData getOrderById(@PathVariable("orderId") String orderId, HttpServletRequest httpServletRequest) {
        OrderDetailRequest request = new OrderDetailRequest();
        request.setOrderId(orderId);

        QueryOrderResponse response = orderQueryService.getOrderById(request);

        if (response.getCode().equals(OrderRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(response.getData());
        }

        return new ResponseUtil().setErrorMsg(response.getMsg());

    }


    /**
     * 删除订单 根据id
     */
    @DeleteMapping("/order/{orderId}")
    public ResponseData deleteOrder(@PathVariable("orderId") Long orderId){

        DeleteOrderRequest request = new DeleteOrderRequest();
        request.setOrderId(orderId.toString());

        DeleteOrderResponse deleteOrder = orderDeleteService.deleteOrder(request);
        if (deleteOrder.getCode().equals(OrderRetCode.SUCCESS.getCode())){
            return new ResponseUtil<>().setData(OrderRetCode.SUCCESS.getMessage());
        }

        return new ResponseUtil<>().setErrorMsg(deleteOrder.getMsg());

    }

}

